package com.sservice.commonBusiness.controller.admin;

import com.sservice.base.entity.dto.BaseResult;
import com.sservice.base.entity.dto.ListResult;
import com.sservice.base.utils.ImgUtils;
import com.sservice.base.utils.RegexUtil;
import com.sservice.commonBusiness.e.File;
import com.sservice.commonBusiness.service.FileService;
import com.sservice.commonBusiness.vo.FileVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by byte_su@163.com on 2018/01/12.
 */
@Controller
@RequestMapping("/admin/file/")
public class FileController {

    @Autowired
    FileService fileService;

    @RequestMapping(value = "add", method = RequestMethod.POST)
    @ResponseBody
    public BaseResult add(File file) {
        return new BaseResult(true, String.valueOf(fileService.insertSelective(file)), 200);
    }

    @RequestMapping(value = "delete", method = RequestMethod.POST)
    @ResponseBody
    public BaseResult delete(@RequestParam Integer id) {
        File file = fileService.selectByPrimaryKey(id);
        ImgUtils.delFile(file.getOriginName()); // 物理删除文件
        return new BaseResult(true, String.valueOf(fileService.deleteByPrimaryKey(id)), 200);
    }

    @RequestMapping(value = "update", method = RequestMethod.POST)
    @ResponseBody
    public BaseResult update(File file) {
        return new BaseResult(true, String.valueOf(fileService.updateByPrimaryKeySelective(file)), 200);
    }

    @RequestMapping("detail/{id}")
    @ResponseBody
    public BaseResult detail(@RequestParam Integer id) {
        File file = fileService.selectByPrimaryKey(id);
        return new BaseResult(true, file);
    }

    @RequestMapping("list")
    @ResponseBody
    public ListResult list(FileVo fileVo) {
        if (Integer.valueOf(0).equals(fileVo.getSysId())) {
            fileVo.setSysId(null);
        }
        return fileService.page(fileVo);
    }

    @RequestMapping(value = "getByUrls", method = RequestMethod.POST)
    @ResponseBody
    public ListResult list(String urls) {

        String[] urls1 = urls.split(RegexUtil.specialCharRegex("|"));
        List<String> strings = new ArrayList<>();
        for (int i = 0; i < urls1.length; i++) {
            strings.add(urls1[i]);
            System.out.println(urls1[i]);
        }
        return new ListResult(true, fileService.getByUrls(strings));
    }

    @RequestMapping(value = "getByDataR", method = RequestMethod.GET)
    @ResponseBody
    public ListResult listDataR(FileVo fileVo) {
        return new ListResult(true, fileService.selectByDataR(fileVo));

    }
}
